package sys

import (
	"errors"
	"gitee.com/freelifer/module-admin/model"
	"gitee.com/freelifer/module-web-base/request"
	"github.com/go-spring/spring-base/util"
	"github.com/go-spring/spring-core/gs"
	uuid "github.com/satori/go.uuid"
	"gorm.io/gorm"
)

func init() {
	// SpringBoot.RegisterBean(new(Service)).AsInterface((*types.FileProvider)(nil))
	gs.Object(new(UserService)).Init(func(c *UserService) {
	})
}

type UserService struct {
	DB *gorm.DB `autowire:""`
}

func (s *UserService) Login(u *model.SysUser) (err error, userInter *model.SysUser) {
	var user model.SysUser
	u.Password = util.MD5(u.Password)
	err = s.DB.Where("username = ? AND password = ?", u.Username, u.Password).Preload("Role").First(&user).Error
	return err, &user
}

func (s *UserService) AddUser(u model.SysUser) (err error, userInter model.SysUser) {
	var user model.SysUser
	if !errors.Is(s.DB.Where("username = ?", u.Username).First(&user).Error, gorm.ErrRecordNotFound) { // 判断用户名是否注册
		return errors.New("用户名已注册"), userInter
	}

	u.Password = util.MD5(u.Password)
	u.UUID = uuid.NewV4()
	err = s.DB.Create(&u).Error
	return err, u
}

func (s *UserService) GetUserInfoList(info request.PageInfo) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := s.DB.Model(&model.SysUser{})
	var userList []model.SysUser
	err = db.Count(&total).Error
	if err != nil {
		return err, userList, total
	}
	err = db.Limit(limit).Offset(offset).Preload("Role").Find(&userList).Error
	return err, userList, total
}

func (s *UserService) DeleteUser(id uint) (err error) {
	var user model.SysUser
	err = s.DB.Where("id = ?", id).Delete(&user).Error
	if err != nil {
		return err
	}
	err = s.DB.Delete(&[]model.SysUseRole{}, "sys_user_id = ?", id).Error
	return err
}
